package com.yq.testmodule.paging3

import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager2
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.yq.testmodule.R
import config.TEST_PAGING3
import kotlinx.coroutines.launch

@Route(path = TEST_PAGING3)
class TestPaging3Activity:AppCompatActivity() {
    private val mAdapter = TestPagingAdapter(this)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.test_activity_paging3)

        val mainViewModel = ViewModelProvider(this).get(TestPagingViewModel::class.java)
        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
        val progressBar = findViewById<ProgressBar>(R.id.progress_bar)
        val refreshLayout = findViewById<SwipeRefreshLayout>(R.id.refreshLayout)
        recyclerView?.layoutManager =
            LinearLayoutManager2(this)
        recyclerView?.adapter = mAdapter
        lifecycleScope.launch {
            mainViewModel.getPagingData().collect { pagingData ->
                mAdapter.submitData(pagingData)
            }
        }
        mAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    progressBar?.visibility = View.INVISIBLE
                    recyclerView?.visibility = View.VISIBLE
                    refreshLayout?.isRefreshing = false

                }
                is LoadState.Loading -> {
                    refreshLayout?.isRefreshing = true
                    progressBar?.visibility = View.VISIBLE
                    recyclerView?.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    progressBar?.visibility = View.INVISIBLE
                    refreshLayout?.isRefreshing = false
                }
            }
        }

        refreshLayout?.setOnRefreshListener {
            recyclerView?.swapAdapter(mAdapter,true)
            mAdapter.refresh()
        }
    }
}